const constants = require('../common/Constants.js');
const umfUtils = require('../utils/UmfUtils.js');
import RpidUtils from '../utils/RpidUtils';
import * as userUtils from '../model/UserUtils';
import UmfLog from '../utils/UmfLog';

const UrlList = {
  urlList: [
      //代理商开户
      constants.Interfaces.FUNC_OPEN_AGENT,
      //查询代理商
      constants.Interfaces.FUNC_SEARCH_AGENT,
      //代理商详情
      constants.Interfaces.FUNC_SEARCH_AGENT_DETAILS,
      //修改代理商详情
      constants.Interfaces.FUNC_MODIFY_AGENTINFO,

      //代理商查询商户
      constants.Interfaces.FUNC_SEARCH_STORES,
      //开通下级代理商获取代理商编号
      constants.Interfaces.FUNC_GET_AGENTID,
      //发送对账邮件
      constants.Interfaces.FUNC_AGENT_SEND_BILLEMAIL,
      //非POS分润汇总查询
      constants.Interfaces.FUNC_SN_POS_OR,
      //非POS分润详细查询
      constants.Interfaces.FUNC_SN_POS_DT,
      //非POS明细邮件
      constants.Interfaces.FUNC_PROFIT_SENDBILLEMAIL,

      //修改业务员权限
      constants.Interfaces.FUNC_SALEMAN_LIMIT_CONF,
      //查询业务员列表
      constants.Interfaces.FUNC_SALESMAN_LIST,
      //查询商铺详情
      constants.Interfaces.FUNC_Merchant_STOREINFO,
      //停用启用业务员
      constants.Interfaces.FUNC_CHANGE_SALEMAN_STATUS,
      //更新业务员权限
      constants.Interfaces.FUNC_CHANGE_SALEMAN_LIMITS
      ],

    contains: function (url) {
        return this.urlList.indexOf(url) >= 0;
    }
};

function requestConfig(){
    //url
    this.url='';
    //请求参数
    this.params={
        //公共参数
        loginUserId: '',
        loginSession: ''
    };
    //是否显示等待对话框
    this.loading = true;
    this.netMethod='POST';
    this.callback={
        httpCallPreFilter: ()=> {
            //网络请求前处理
            if (this.loading) {
                wx.showToast({
                    title: '加载中',
                    icon: 'loading',
                    mask: true,
                    duration: 30000,
                });
            }
        },
        httpCallBackPreFilter: (response)=> {
            //网络请求返回数据预处理
        },
        doHttpSucess: (response)=> {
            //网络请求成功--公共处理
        },
        doHttpFailure : (response)=> {
            //网络请求失败--公共处理
            wx.showModal({
                title: '提示',
                content: response.retMsg,
                showCancel: false
            });
        },
        doComplete: ()=> {
            //网络请求结束--公共处理
            if (this.loading) {
                //wx.hideToast();
            }
        }
    };

    this.setMethodGet = function(){
        this.netMethod = 'GET';
        return this;
    };

    this.send = function(){
        _request(this);
    };

    this.upload = function (filePath) {
        _upload(this, filePath);
    }
}

function httpResponse() {
    //服务器返回结果数据
    this.result = '';
    //rpid
    this.rpid = '';
    //服务器返回消息
    this.retMsg = '';
    //结果码
    this.retCode = '';
    //请求配置信息
    this.requestConfig = {};

    this.isSucess = ()=> {
        return constants.RetCodes.SUCCESS === this.retCode;
    };

    this.create = (retCode, retMsg, rpid, result)=> {
        this.result = result;
        this.rpid = rpid;
        this.retMsg = retMsg;
        this.retCode = retCode;
        return this;
    };
}

/**
 * 注意,此方法调用后还要调用.send()才是发送出去.
 * @param url
 * @param params
 * @param callback  拷贝上方注释区的代码使用
 * @param loading
 * @returns {requestConfig}
 */

function buildRequest(url, params, callback, loading = true){
    let config = new requestConfig();
    config.loading = loading;

    config.url = constants.DANGBAN_URL + url;
    config.params = params;

    if (_isFunction(callback.httpCallPreFilter)) {
        let pubHttpCallPreFilter = config.callback.httpCallPreFilter;
        config.callback.httpCallPreFilter = () => {
            if (!callback.httpCallPreFilter()) {
                pubHttpCallPreFilter();
            }
        }
    }
    if (_isFunction(callback.httpCallBackPreFilter)) {
        let pubHttpCallBackPreFilter = config.callback.httpCallBackPreFilter;
        config.callback.httpCallBackPreFilter = (response) => {
            if (!callback.httpCallBackPreFilter(response)) {
                pubHttpCallBackPreFilter(response);
            }
        }
    }
    if (_isFunction(callback.doHttpSucess)) {
        let pubDoHttpSucess = config.callback.doHttpSucess;
        config.callback.doHttpSucess = (response) => {
            if (!callback.doHttpSucess(response)) {
                pubDoHttpSucess(response);
            }
        }
    }
    if (_isFunction(callback.doHttpFailure)) {
        let pubDoHttpFailure = config.callback.doHttpFailure;
        config.callback.doHttpFailure = (response) => {
            if (!callback.doHttpFailure(response)) {
                pubDoHttpFailure(response);
            }
        }
    }

    if (_isFunction(callback.doComplete)) {
        let pubDoComplete = config.callback.doComplete;
        config.callback.doComplete = () => {
            if (!callback.doComplete()) {
                pubDoComplete();
            }
        }
    }
    return config;
}

/**
 * 请求数据
 * @param requestConfig
 * @private
 */
function _request(requestConfig){
    //请求发出前
    requestConfig.callback.httpCallPreFilter();
    //添加公共参数
    _addCommonParams(requestConfig.params);

    UmfLog.log("url:::" + requestConfig['url']);
    UmfLog.log("netMethod:::" + requestConfig['netMethod']);
    UmfLog.log(requestConfig['params']);
    wx.request({
        url: requestConfig['url'],
        method: requestConfig['netMethod'],
        data: requestConfig['params'],
        header: {'Content-Type':'application/json'},
        success: (res)=> {
            wx.hideToast();
            UmfLog.log(res);
            _requestSuccess(res, requestConfig);
        },
        fail: (res)=> {
            wx.hideToast();
            _requestFailed(res, requestConfig)
        },
        complete: (res)=> {
            requestConfig.callback.doComplete();
        }
    })
}

/**
 * 上传文件
 * @param requestConfig
 * @param filePath
 * @private
 */
function _upload(requestConfig, filePath) {
    //请求发出前
    requestConfig.callback.httpCallPreFilter();
    //添加公共参数
    _addCommonParams(requestConfig.params);

    wx.uploadFile({
        url: requestConfig['url'], //仅为示例，非真实的接口地址
        filePath: filePath,
        name: 'file',
        formData: requestConfig['params'],
        success: (res)=> {
            UmfLog.log(res);
            _requestSuccess(res, requestConfig);
        },
        fail: (res)=> {
            _requestFailed(res, requestConfig);
        },
        complete: ()=> {
            requestConfig.callback.doComplete();
        }
    })

}

function _callBack(response, callback) {
    if (callback) {
        if (response["retCode"] === "-1") {
            callback.doHttpFailure(response);
        } else {
            if (!callback.httpCallBackPreFilter(response)) {
                callback.doHttpSucess(response);
            }
        }
    }
}

function _requestSuccess(res, requestConfig) {
    if (parseInt(res.statusCode) === 200) {
        let response = res['data'];
        if (response && typeof response === 'Object') {
            response.requestConfig = requestConfig;
        }

        _callBack(response, requestConfig.callback);
    } else {
        let response = new httpResponse().create(constants.RetCodes.RESPONSE_ERROR, '请求失败');
        response.requestConfig = requestConfig;
        requestConfig.callback.doHttpFailure(response);
    }
}

function _requestFailed(res, requestConfig) {
    UmfLog.log("fail",res);
    let response = new httpResponse().create(constants.RetCodes.NETWORK_ERROR, '网络错误');
    response.requestConfig = requestConfig;
    requestConfig.callback.doHttpFailure(response);
}

// /**
//  * 添加公共参数
//  * @param params
//  * @private
//  */
// function _addCommonParams(params) {
//     let loginUserId= umfUtils.getStorageSync(constants.Keys.USER_ID);
//     let loginSession = umfUtils.getStorageSync(constants.Keys.SEESION);
//     let rpid = RpidUtils.getRpid();
//
//     //添加公共参数
//     params["version"] = "1";
//     params["loginUserId"] = loginUserId;
//     params["loginSession"] = loginSession;
//     params["rpid"] = rpid;
// }

/**
 * 添加公共参数
 * @param params
 * @private
 */
function _addCommonParams(params) {
    let userInfo = new userUtils.userInfo().get();
    let loginUserId= userInfo.userId;
    let loginAssistId= userInfo.assistId;
    let loginSession = umfUtils.getStorageSync(constants.Keys.SEESION);
    let loginAgentId = userInfo.agentId;
    let rpid = RpidUtils.getRpid();

    //添加公共参数
    params["version"] = "1";
    params["loginUserId"] = loginUserId;
    params["loginAssistId"] = loginAssistId;
    params["loginAgentId"] = loginAgentId;
    params["rpid"] = rpid;

    if (!params["code"]) {
        params["loginToken"] = loginSession;
    }
}

function _isFunction(func) {
    if (typeof func === "function") {
        return true;
    }
    return false;
}

module.exports = {
    buildRequest: buildRequest,
    UrlList: UrlList
};